import { NextRequest, NextResponse } from 'next/server'
import { BaseController } from './base.controller'
import { SheetService } from '../services/sheet.service'
import { UserService } from '../services/user.service'
import { CreateSheetData, UpdateSheetData } from '../services/sheet.service'

export class SheetController extends BaseController {
  private sheetService: SheetService
  private userService: UserService

  constructor() {
    super()
    this.sheetService = new SheetService()
    this.userService = new UserService() // 确保 UserService 被创建并注册
  }

  // 获取用户的表格列表
  async getUserSheets(request: NextRequest): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const userId = await this.getUserIdFromRequest(request)
      return await this.sheetService.getUserSheets(userId)
    }, 'Failed to fetch user sheets')
  }

  // 创建表格
  async createSheet(request: NextRequest): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const userId = await this.getUserIdFromRequest(request)
      const body = await request.json()
      
      const createData: CreateSheetData = {
        title: body.title,
        description: body.description,
        ownerId: userId
      }

      if (!createData.title) {
        throw new Error('Title is required')
      }

      return await this.sheetService.createSheet(createData)
    }, 'Failed to create sheet')
  }

  // 获取表格详情
  async getSheetById(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      let userId: string | undefined

      // 调试信息
      console.log('=== Sheet Access Debug ===')
      console.log('Sheet ID:', sheetId)
      console.log('Request URL:', request.url)
      console.log('Authorization header:', request.headers.get('authorization'))

      try {
        userId = await this.getUserIdFromRequest(request)
        console.log('User ID from request:', userId)
      } catch (error) {
        console.log('User authentication failed:', error instanceof Error ? error.message : 'Unknown error')
        // 用户未认证，继续检查是否为公开表格
      }

      const sheet = await this.sheetService.getSheetById(sheetId)
      console.log('Sheet found:', !!sheet)
      console.log('Sheet isPublic:', sheet?.isPublic)
      console.log('Sheet ownerId:', sheet?.ownerId)
      
      if (!sheet) {
        throw new Error('Sheet not found')
      }

      // 检查权限
      if (userId) {
        const permission = await this.sheetService.checkUserPermission(sheetId, userId)
        console.log('User permission:', permission)
        if (!permission.canView) {
          throw new Error('Permission denied')
        }
      } else if (!sheet.isPublic) {
        console.log('Sheet is not public and user is not authenticated')
        throw new Error('Authentication required')
      }

      console.log('Access granted to sheet')
      return sheet
    }, 'Failed to fetch sheet')
  }

  // 更新表格
  async updateSheet(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      const userId = await this.getUserIdFromRequest(request)
      const body = await request.json()

      // 检查权限
      const permission = await this.sheetService.checkUserPermission(sheetId, userId)
      if (!permission.canEdit) {
        throw new Error('Permission denied')
      }

      const updateData: UpdateSheetData = {
        title: body.title,
        description: body.description,
        isPublic: body.isPublic,
        allowEdit: body.allowEdit
      }

      return await this.sheetService.updateSheet(sheetId, updateData)
    }, 'Failed to update sheet')
  }

  // 删除表格
  async deleteSheet(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      const userId = await this.getUserIdFromRequest(request)

      // 检查权限
      const permission = await this.sheetService.checkUserPermission(sheetId, userId)
      if (!permission.canDelete) {
        throw new Error('Permission denied')
      }

      await this.sheetService.deleteSheet(sheetId)
      return { success: true }
    }, 'Failed to delete sheet')
  }

  // 保存表格数据
  async saveSheetData(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      const userId = await this.getUserIdFromRequest(request)
      const body = await request.json()

      // 检查权限
      const permission = await this.sheetService.checkUserPermission(sheetId, userId)
      if (!permission.canEdit) {
        throw new Error('Permission denied')
      }

      const { cells, title, description } = body

      // 更新表格基本信息
      if (title || description !== undefined) {
        await this.sheetService.updateSheet(sheetId, { title, description })
      }

      // 保存单元格数据
      if (cells && Array.isArray(cells)) {
        await this.sheetService.saveCells(sheetId, cells)
      }

      return { success: true, message: 'Sheet saved successfully' }
    }, 'Failed to save sheet data')
  }

  // 获取表格单元格
  async getSheetCells(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      let userId: string | undefined

      try {
        userId = await this.getUserIdFromRequest(request)
      } catch (error) {
        // 用户未认证，继续检查是否为公开表格
      }

      // 检查权限
      if (userId) {
        const permission = await this.sheetService.checkUserPermission(sheetId, userId)
        if (!permission.canView) {
          throw new Error('Permission denied')
        }
      } else {
        const sheet = await this.sheetService.getSheetById(sheetId)
        if (!sheet || !sheet.isPublic) {
          throw new Error('Authentication required')
        }
      }

      return await this.sheetService.getSheetCells(sheetId)
    }, 'Failed to fetch sheet cells')
  }

  // 更新单个单元格
  async updateCell(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      const userId = await this.getUserIdFromRequest(request)
      const body = await request.json()

      // 检查权限
      const permission = await this.sheetService.checkUserPermission(sheetId, userId)
      if (!permission.canEdit) {
        throw new Error('Permission denied')
      }

      const { row, column, value, formula, style } = body

      if (typeof row !== 'number' || typeof column !== 'number') {
        throw new Error('Row and column must be numbers')
      }

      return await this.sheetService.updateCell(sheetId, row, column, value, formula, style)
    }, 'Failed to update cell')
  }

  // 添加成员
  async addMember(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      const userId = await this.getUserIdFromRequest(request)
      const body = await request.json()

      // 检查权限
      const permission = await this.sheetService.checkUserPermission(sheetId, userId)
      if (!permission.canShare) {
        throw new Error('Permission denied')
      }

      const { memberUserId, role } = body

      if (!memberUserId) {
        throw new Error('Member user ID is required')
      }

      return await this.sheetService.addMember(sheetId, memberUserId, role)
    }, 'Failed to add member')
  }

  // 移除成员
  async removeMember(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      const userId = await this.getUserIdFromRequest(request)
      const body = await request.json()

      // 检查权限
      const permission = await this.sheetService.checkUserPermission(sheetId, userId)
      if (!permission.canShare) {
        throw new Error('Permission denied')
      }

      const { memberUserId } = body

      if (!memberUserId) {
        throw new Error('Member user ID is required')
      }

      await this.sheetService.removeMember(sheetId, memberUserId)
      return { success: true }
    }, 'Failed to remove member')
  }

  // 生成分享链接
  async generateShareLink(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      const userId = await this.getUserIdFromRequest(request)

      // 检查权限
      const permission = await this.sheetService.checkUserPermission(sheetId, userId)
      if (!permission.canShare) {
        throw new Error('Permission denied')
      }

      const token = await this.sheetService.generateShareToken(sheetId)
      return { shareToken: token, shareUrl: `/sheet/${sheetId}?token=${token}` }
    }, 'Failed to generate share link')
  }

  // 通过分享token访问表格
  async accessByShareToken(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
    return this.handleAsync(async () => {
      const sheetId = params.id
      const { searchParams } = new URL(request.url)
      const token = searchParams.get('token')

      if (!token) {
        throw new Error('Share token is required')
      }

      const sheet = await this.sheetService.getSheetByShareToken(token)
      
      if (!sheet || sheet.id !== sheetId) {
        throw new Error('Invalid share token')
      }

      return sheet
    }, 'Failed to access sheet by share token')
  }
}
